from datetime import datetime

from PyQt5.QtWidgets import QWidget, QFormLayout, QLineEdit, \
    QLabel, QPushButton, QComboBox, QGroupBox, QRadioButton, QHBoxLayout
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.interval import IntervalTrigger

from news_2.src.main import store
from news_2.src.main.HtmlXPathParser import LxmlExtractNews


class SchedulerViewForm(QWidget):
    def __init__(self):
        super().__init__()
        self.web_data = {}
        self.minutes = 0
        self.seconds = 5
        self.is_running = False
        self.scheduler = BackgroundScheduler()
        self.add_job()
        self.initUI()

    def initUI(self):
        self.layout = QFormLayout()

        self.create_groupbox()
        self.create_statr_button()

        self.setLayout(self.layout)
        self.setWindowTitle('IntervalTrigger Form')

    def create_line_edit(self):
        # 创建布局
        layout = QFormLayout()

        # 创建输入框和标签
        self.minutes_input = QLineEdit()
        self.seconds_input = QLineEdit()

        # 添加到布局
        layout.addRow(QLabel('分钟:'), self.minutes_input)
        layout.addRow(QLabel('秒钟:'), self.seconds_input)

        # 创建提交按钮
        submit_button = QPushButton('保存')
        submit_button.clicked.connect(self.submit_line_edit)

        # 添加按钮到布局
        layout.addRow(submit_button)

        # 设置布局
        self.setLayout(layout)

    def create_combobox_ui(self):
        layout = QFormLayout()

        # 创建一个 QComboBox 供选择
        self.minutes_combobox = QComboBox()
        self.seconds_combobox = QComboBox()

        # 添加选项到 QComboBox
        self.minutes_combobox.addItems(['20', '30', '60', '120'])
        self.seconds_combobox.addItems(['20', '30', '60', '120'])

        # 创建标签
        layout.addRow(QLabel('Minutes:'), self.minutes_combobox)
        layout.addRow(QLabel('Seconds:'), self.seconds_combobox)

        # 创建提交按钮
        self.submit_button = QPushButton('保存')
        self.submit_button.clicked.connect(self.submit_combobox)
        layout.addRow(self.submit_button)

        self.setLayout(layout)
        self.setWindowTitle('IntervalTrigger Form')

    def create_groupbox(self):
        # 创建分钟和秒数的单选按钮组
        self.minutes_group = QGroupBox("分钟")
        self.seconds_group = QGroupBox("秒种")

        self.minutes_buttons = [QRadioButton(str(x)) for x in [0, 20, 30, 60, 120]]
        self.seconds_buttons = [QRadioButton(str(x)) for x in [5, 20, 30, 60, 120]]

        # 添加单选按钮到组
        # 为每个单选按钮添加点击事件
        # 通过索引来引用按钮
        minutes_layout = QHBoxLayout()
        for j, button in enumerate(self.minutes_buttons):
            button.toggled.connect(lambda checked, index=j: self.submit_groupbox())  # 通过索引来引用按钮
            minutes_layout.addWidget(button)
        self.minutes_group.setLayout(minutes_layout)

        # 为每个单选按钮添加点击事件
        # 通过索引来引用按钮
        seconds_layout = QHBoxLayout()
        for j, button in enumerate(self.seconds_buttons):
            button.toggled.connect(lambda checked, index=j: self.submit_groupbox())
            seconds_layout.addWidget(button)
        self.seconds_group.setLayout(seconds_layout)

        # 默认选中第一个按钮
        self.minutes_buttons[0].setChecked(True)
        self.seconds_buttons[0].setChecked(True)

        # 添加到布局
        self.layout.addRow(self.minutes_group)
        self.layout.addRow(self.seconds_group)

    def create_statr_button(self):
        # 创建一个垂直布局
        layout = self.layout

        # 添加开始/关闭控件
        self.button = QPushButton("开始", self)

        self.button.setCheckable(True)
        self.button.clicked.connect(self.toggle_start_stop)
        layout.addWidget(self.button)

        # 设置布局
        self.setLayout(layout)

    """
        处理数据 时间监听
    """

    # 监听开始按钮的状态
    def toggle_start_stop(self):
        if self.button.isChecked():
            self.button.setText("停止")
            # 执行开始操作
            self.scheduler_start_job()
        else:
            self.button.setText("开始")
            # 执行停止操作
            self.scheduler_stop_job()

    def submit_line_edit(self):
        # 获取用户输入
        minutes = self.minutes_input.text()
        seconds = self.minutes_input.text()

        try:
            # 转换为整数并创建 IntervalTrigger
            minutes = int(minutes) if minutes else 0
            seconds = int(seconds) if seconds else 0
            trigger = IntervalTrigger(minutes=minutes, seconds=seconds)
            print(f"Created IntervalTrigger: {trigger}")

        except ValueError:
            print("Invalid input. Please enter valid numbers.")

    def submit_combobox(self):
        # 获取 QComboBox 中选定的值
        minutes = self.minutes_combobox.currentText()
        seconds = self.seconds_combobox.currentText()
        trigger = IntervalTrigger(minutes=minutes, seconds=seconds)
        print(f"Created IntervalTrigger: {trigger}")

    def submit_groupbox(self):
        print("提交选择")
        # 获取选中的 QRadioButton 的值
        minutes = self.get_checked_value(self.minutes_buttons)
        seconds = self.get_checked_value(self.seconds_buttons)
        # TODO 存值
        print(f"minutes: {minutes}, seconds: {seconds}")

    def get_checked_value(self, buttons):
        for button in buttons:
            if button.isChecked():
                return button.text()
        return None

    def scheduler_start_job(self):
        print("正在启动定时任务")
        self.is_running = True
        self.web_scraper()
        self.scheduler.start()

    def scheduler_stop_job(self):
        print("正在结束定时任务")
        self.scheduler.shutdown()

    def add_job(self):
        self.scheduler.add_job(self.web_scraper, IntervalTrigger(minutes=self.minutes, seconds=self.seconds))

    def web_scraper(self):
        now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        print(f"本轮执行时间：{now} ++++++++++++++++++++++++++++++++++++++++++++++++++++++\n")
        web_list = store.get_store().dispatch("get_web_table")
        for web in web_list:
            if web['start'] == 0:
                continue
            print(f"key:{web['key']}抓取中------------------------------------------------")
            news = LxmlExtractNews(web['url'], web['encode'], web['decode'])
            news.request_html_content()
            news.decode_html()
            news.build_html_tags(web['html_tag'])
            news.process_html_tag_data()
            data = []
            for item in news.tags:
                print(f"{item.key}:{item.get_data_value()}")
                str_tag = f"{item.key}:{item.get_data_value()}"
                data.append(str_tag)
            self.web_data['key'] = data
        # TODO 记录日志 并比对内容是否发布
